<?php 


function send_mail(){
	global $smarty;
	//$config = obtain_config();
$mail = request_var("mail",'');
$body = request_var("body",'');

if (!check_code('kontakt') || $body=='' || $mail='' ){
	
		$info_mail = "Nezadali jste správný kód nebo vzkaz<br />";		
}
else{
include_once($root_path . 'includes/mailer/class.phpmailer.php');
		//request_var("");
		$body =  $smarty->fetch('email.html') ;			
		//$prijemce = "martinscheidel@seznam.cz";			
		$prijemce = "jirka.holusa@seznam.cz";
		//$mail = new PHPMailer();
		$mail = new PHPMailer();
		$mail->IsMail(); 
		$mail->IsHTML(true);     
  		$mail->CharSet  = "utf-8"; 
		$mail->From     = "poptavka@auta-fr.cz";
  		$mail->FromName = "objednavky";
  		$mail->WordWrap = 50;    
  		//$mail->AddStringAttachment ($data, "zakaznik.txt", "base64", "text/plain");
  		$mail->Subject  =  "Nová poptávka";
  		$mail->Body     =  $body; //
  		$mail->AltBody  =  "";
	    $mail->AddAddress($prijemce,$prijemce); 
     	if(!$mail->Send())
	    {
	    	$info_mail = "<p>Nepodařilo se odeslat vzkaz <p>";
	    	$info_mail .= "došlo k chybě: " . $mail->ErrorInfo;	  	
	    }
	  	else{
			$info_mail .= "Mail odeslán"; 
	}

}
unset($mail);
unset($body);
	
	
	
	
	
	
}

  // nacte konfiguraci
	function obtain_config()
	{
		global $db;
		
			$sql = 'SELECT config_name, config_value
				FROM ' . CONFIG_TABLE.' ;' ;
			//	echo $sql;
			$result = $db->prepare($sql);
       $result->execute();
			while ($row = $result->fetch_assoc())
			{
				$config[$row['config_name']] = $row['config_value'];
			}
		//	$db->sql_freeresult($result);
	

	
		return $config;
	}

/**
* Check the code
*/
function check_code($name)
{
	$code_name = "code_{$name}";
	$post_code = request_var($code_name, '');
	$sess_code = isset($_SESSION[$code_name]) ? $_SESSION[$code_name] : '';

	if ($post_code == '' || $sess_code == '')
	{
		return false;
	}
	
	return $post_code == $sess_code;
}
	
/**
* Get code
*/
function get_code($name, $max = 9999)
{
	$code = rand(1001, $max);

	$_SESSION["code_{$name}"] = $code;

	return $code;
}
	
/**
* Build string formated for uri
*/
function format_url($string)
{
	$url = $string;
	$url = preg_replace('~[^\\pL0-9_]+~u', '-', $url);
	$url = trim($url, "-");
	$url = iconv("utf-8", "us-ascii//TRANSLIT", $url);
	$url = strtolower($url);
	$url = preg_replace('~[^-a-z0-9_]+~', '', $url);
    return $url;
}

/**
* set_var
*
* Set variable, used by {@link request_var the request_var function}
*
* @access: private
*/
function set_var(&$result, $var, $type, $multibyte = false)
{
	settype($var, $type);
	$result = $var;

	if ($type == 'string')
	{
		$result = trim(htmlspecialchars(str_replace(array("\r\n", "\r"), array("\n", "\n"), $result)));
		$result = (STRIP) ? stripslashes($result) : $result;

		// Check for possible multibyte characters to save a preg_replace call if nothing is in there...
		if ($multibyte && strpos($result, '&amp;#') !== false)
		{
			$result = preg_replace('#&amp;(\#[0-9]+;)#', '&\1', $result);
		}
	}
}

/**
* request_var
*
* Used to get passed variable
*/
function request_var($var_name, $default, $multibyte = false)
{
	if (!isset($_REQUEST[$var_name]) || (is_array($_REQUEST[$var_name]) && !is_array($default)) || (is_array($default) && !is_array($_REQUEST[$var_name])))
	{
		return (is_array($default)) ? array() : $default;
	}

	$var = $_REQUEST[$var_name];
	if (!is_array($default))
	{
		$type = gettype($default);
	}
	else
	{
		list($key_type, $type) = each($default);
		$type = gettype($type);
		$key_type = gettype($key_type);
	}

	if (is_array($var))
	{
		$_var = $var;
		$var = array();

		foreach ($_var as $k => $v)
		{
			if (is_array($v))
			{
				foreach ($v as $_k => $_v)
				{
					set_var($k, $k, $key_type);
					set_var($_k, $_k, $key_type);
					set_var($var[$k][$_k], $_v, $type, $multibyte);
				}
			}
			else
			{
				set_var($k, $k, $key_type);
				set_var($var[$k], $v, $type, $multibyte);
			}
		}
	}
	else
	{
		set_var($var, $var, $type, $multibyte);
	}

	return $var;
}
function login_box($redirect = '', $l_explain = '', $l_success = '', $admin = false, $s_display = true)
{
	global $db, $user, $smarty, $root_path, $config;

	$err = '';
  
	// Make sure user->setup() has been called
	if (empty($user->lang))
	{
		$user->setup();
	}
	
  //print_r($_POST);
	if (isset($_POST['login']))
	{

		$username	= request_var('username', '', true);
		$password	= request_var('password', '');
		$autologin	= (!empty($_POST['autologin'])) ? true : false;
		$viewonline = (!empty($_POST['viewonline'])) ? 0 : 1;
		$admin 		= ($admin) ? 1 : 0;
    
		// If authentication is successful we redirect user to previous page
		$result = $user->login($username, $password, $autologin, $viewonline, $admin);
    
		// The result parameter is always an array, holding the relevant informations...
		if ($result['status'] == LOGIN_SUCCESS)
		{
      		 
			$redirect = request_var('redirect', "{$root_path}index.php");
			$message = ($l_success) ? $l_success : 'Nejsi prihlasen';
			$l_redirect = ($admin) ? $user->lang['PROCEED_TO_ACP'] : (($redirect === "{$root_path}index.php") ? 'index.php' :'index.php' );

			// append/replace SID (may change during the session for AOL users)
			$redirect = reapply_sid($redirect);

			// old way
			meta_refresh(1, $redirect);
		//	trigger_error($message . '<br /><br />' . sprintf($l_redirect, '<a href="' . $redirect . '">', '</a>'));
		}

		// Something failed, determine what...
		if ($result['status'] == LOGIN_BREAK)
		{
			trigger_error($result['error_msg'], E_USER_ERROR);
			
		}

		// Error
		$err = $user->lang[$result['error_msg']];
	
		// Assign admin contact to some error messages
	
	}

	if (!$redirect)
	{
		// We just use what the session code determined...
		$redirect = $user->page['page_name'] . (($user->page['query_string']) ? '?' . $user->page['query_string'] : '');
	}


}


// Server functions (building urls, redirecting...)

/**
* Append session id to url
*
* @param string $url The url the session id needs to be appended to (can have params)
* @param mixed $params String or array of additional url parameters
* @param bool $is_amp Is url using &amp; (true) or & (false)
* @param string $session_id Possibility to use a custom session id instead of the global one
*
* Examples:
* <code>
* append_sid("{$phpbb_root_path}viewtopic.$phpEx?t=1&amp;f=2");
* append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&amp;f=2');
* append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=1&f=2', false);
* append_sid("{$phpbb_root_path}viewtopic.$phpEx", array('t' => 1, 'f' => 2));
* </code>
*/
function append_sid($url, $params = false, $is_amp = true, $session_id = false)
{
	global $user, $_EXTRA_URL;

	$amp_delim = ($is_amp) ? '&amp;' : '&';
	$url_delim = (strpos($url, '?') === false) ? '?' : $amp_delim;

	$session_id = $user->data['is_bot'] ? '' : (defined('NEED_SID') ? session_name() . '=' . session_id() : SID);

	// Appending custom url parameter?
	$append_url = (!empty($_EXTRA_URL)) ? implode($amp_delim, $_EXTRA_URL) : '';

	// Use the short variant if possible ;)
	if ($params === false)
	{
		// Append session id
		return (!$session_id) ? $url . (($append_url) ? $url_delim . $append_url : '') : $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $session_id;
	}

	// Build string if parameters are specified as array
	if (is_array($params))
	{
		$output = array();

		foreach ($params as $key => $item)
		{
			if ($item === NULL)
			{
				continue;
			}

			$output[] = $key . '=' . $item;
		}

		$params = implode($amp_delim, $output);
	}

	// Append session id and parameters (even if they are empty)
	// If parameters are empty, the developer can still append his/her parameters without caring about the delimiter
	return $url . (($append_url) ? $url_delim . $append_url . $amp_delim : $url_delim) . $params . ((!$session_id) ? '' : $amp_delim . $session_id);
}


/**
* Generate page header
*/
function page_header($page_title = '')
{
	global $smarty, $db, $config, $host, $user, $_SID, $root_path, $nabidka, $search, $abs_prefix;
  global $cart;
	if (defined('HEADER_INC'))
	{
		return;
	}

	define('HEADER_INC', true);

	// Generate logged in/logged out status
	if ($user->data['user_id'] != ANONYMOUS)
	{
		$u_login_logout = append_sid("{$root_path}ucp.php", 'mode=logout');
		$l_login_logout = sprintf($user->lang['ODHLASIT_UZIVATELE'], $user->data['username']);
		$l_login_label 	= $user->lang['ODHLASENI'];
	}
	else
	{
		$u_login_logout = append_sid("{$root_path}ucp.php", 'mode=login');
		$l_login_logout = $user->lang['PRIHLASENI'];
		$l_login_label 	= $user->lang['PRIHLASENI'];
	}
	
	/**
	 *  Odkazy na 4 posledni auta
	 */
		$sql = "SELECT id,model,znacka FROM ".TBL_AUTA." ORDER BY id DESC LIMIT 6 ";
		$stmt = $db->prepare($sql)->execute();
		$linky = array();
		while($row = $stmt->fetch_assoc()){
			$linky[] = $row;	
		}
		$smarty->assign('linky',$linky);

	// cart info
//	$cart->show_info();

	
//	// gen code for panel
	//get_code('kontakt');
//	$template->assign_var('U_CODE_KONTAKT', append_sid($abs_prefix . '/image.php', 'name=kontakt'));

	// valid user page
	$user_page = str_replace("&", "&amp;", $user->page['page']);

	//
	// The following assigns all _common_ variables that may be used at any point
	// in a template.
	//
	$smarty->assign(array(
		'PAGE_TITLE'		=> $page_title,
		'DOMAIN'			=> $host['domena'], // zrusit
		'DOMENA'			=> $host['domena'],
		'ROK'				=> date("Y"),
		'HOTLINE'			=> '724 247 663',
		
		'SHOP_EMAIL'		=> 'obchod@' . strtolower($host['domena']),
		'SHOP_SKYPE'		=> 'petrbarumpneu',
		'SHOP_TEL'			=> '724 247 663',
		'SHOP_ICQ'			=> '395 248 701',

		'GOOGLE_ANALYTICS'	=> $host['id'],

		'S_HIDDEN_SID'		=> $_SID != '' ? build_hidden_fields(array('sid'	=> $_SID)) : '',
		'SID'				=> $_SID != '' ? build_hidden_fields(array('sid'	=> $_SID)) : '',
		'_SID'				=> $_SID,
		'SESSION_ID'		=> $user->session_id,
		'ROOT_PATH'			=> $root_path,
		'YEAR'				=> date("Y"),

		'L_LOGIN_LOGOUT'	=> $l_login_logout,
		'L_LOGIN_LABEL'		=> $l_login_label,
		'U_LOGIN_LOGOUT'	=> $u_login_logout,
		'U_LOGIN'			=> append_sid($abs_prefix . '/ucp.php', 'mode=login'),

		'S_USER_LOGGED_IN'	=> $user->data['user_id'] != ANONYMOUS ? true : false,
		'S_USER_ADMIN'		=> $user->data['user_type'] == USER_FOUNDER ? true : false,

		//'VYROBCI_PNEU'		=> implode("\n", $vyrobci[PNEU]),
		//'VYROBCI_ALU'		=> implode("\n", $vyrobci[ALU]),

		
		'U_SELF'			=> append_sid($user_page),
		'U_DEBUG_EXPLAIN'	=> append_sid($user_page, 'explain=1'),

				//'PNEU_KATEGORIE_LIST'	=> implode(' | ', $pneu_kategorie),
		
		'U_PRINT'			=> append_sid($user_page, 'tisk=1'),

		'T_THEME_PATH'			=> $abs_prefix . "/img/theme/",
		'T_TEMPLATE_PATH'		=> $abs_prefix . "/styles/" . $host['template'] . '/template/',
		'T_IMAGESET_PATH'		=> $abs_prefix . "/styles/" . $host['template'] . '/imageset/',
		'T_IMAGESET_LANG_PATH'	=> $abs_prefix . "/styles/" . $host['template'] . '/imageset/' . $user->data['user_lang'],
		'IMAGES_PATH'			=> $host['image_path'],
		'T_STYLESHEET_LINK'		=> $abs_prefix . "/styles/" . $host['template'] . '/theme/stylesheet.css',
		'T_STYLESHEET_PRINT'	=> $abs_prefix . "/styles/" . $host['template'] . '/theme/print.css',


		'BLANK_MALY'			=> 'blank/maly.gif',
		'BLANK_STREDNI'			=> 'blank/stredni.gif',
		'BLANK_VELKY'			=> 'blank/velky.gif',

		'SITE_LOGO_IMG'			=> $host['lista']
	));

	//header('Content-type: text/html; charset=utf-8');
//	header('Cache-Control: private, no-cache="set-cookie", pre-check=0, post-check=0');
	//header('Expires: 0');
	//header('Pragma: no-cache');
	
	return;
}




/**
* Build simple hidden fields from array
*/
function build_hidden_fields($field_ary)
{
	$s_hidden_fields = '';

	foreach ($field_ary as $name => $vars)
	{
		if (is_array($vars))
		{
			foreach ($vars as $key => $value)
			{
				$s_hidden_fields .= '<input type="hidden" name="' . $name . '[' . $key . ']" value="' . $value . '" />';
			}
		}
		else
		{
			$s_hidden_fields .= '<input type="hidden" name="' . $name . '" value="' . $vars . '" />';
		}
	}

	return $s_hidden_fields;
}

/**
* Re-Apply session id after page reloads
*/
function reapply_sid($url)
{
	global $root_path;

	if ($url === 'index.php')
	{
		return append_sid('index.php');
	}
	else if ($url === "{$root_path}index.php")
	{
		return append_sid("{$root_path}index.php");
	}

	// Remove previously added sid
	if (strpos($url, '?sid=') !== false)
	{
		$url = preg_replace('/(\?)sid=[a-z0-9]+(&amp;|&)?/', '\1', $url);
	}
	else if (strpos($url, '&sid=') !== false)
	{
		$url = preg_replace('/&sid=[a-z0-9]+(&)?/', '\1', $url);
	}
	else if (strpos($url, '&amp;sid=') !== false)
	{
		$url = preg_replace('/&amp;sid=[a-z0-9]+(&amp;)?/', '\1', $url);
	}

	return append_sid($url);
}


/**
* Redirects the user to another page then exits the script nicely
*/
function redirect($url, $code = 302)
{
	global $db, $config, $user;

	if (isset($db))
	{
		//$db->sql_close();
	}



	// Make sure no &amp;'s are in, this will break the redirect
	$url = str_replace('&amp;', '&', $url);

	// Make sure no linebreaks are there... to prevent http response splitting for PHP < 4.4.2
	if (strpos(urldecode($url), "\n") !== false || strpos(urldecode($url), "\r") !== false)
	{
		trigger_error('Tried to redirect to potentially insecure url.', E_USER_ERROR);
	}

	// Determine which type of redirect we need to handle...
	$url_parts = parse_url($url);

	if ($url_parts === false)
	{
		// Malformed url, redirect to current page...
		$url = generate_board_url() . '/' . $user->page['page'];
	}
	else if (!empty($url_parts['scheme']) && !empty($url_parts['host']))
	{
		// Full URL
	}
	else if ($url{0} == '/')
	{
		// Absolute uri, prepend direct url...
		$url = generate_board_url(true) . $url;
	}
	else
	{
		// Relative uri
		$pathinfo = pathinfo($url);

		// Is the uri pointing to the current directory?
		if ($pathinfo['dirname'] == '.')
		{
			if ($user->page['page_dir'])
			{
				$url = generate_board_url() . '/' . $user->page['page_dir'] . '/' . str_replace('./', '', $url);
			}
			else
			{
				$url = generate_board_url() . '/' . str_replace('./', '', $url);
			}
		}
		else
		{
			// Get the realpath of dirname
			$root_dirs = explode('/', str_replace('\\', '/', realpath('./')));
			$page_dirs = explode('/', str_replace('\\', '/', realpath($pathinfo['dirname'])));
			$intersection = array_intersect_assoc($root_dirs, $page_dirs);

			$root_dirs = array_diff_assoc($root_dirs, $intersection);
			$page_dirs = array_diff_assoc($page_dirs, $intersection);

			$dir = str_repeat('../', sizeof($root_dirs)) . implode('/', $page_dirs);

			if ($dir && substr($dir, -1, 1) == '/')
			{
				$dir = substr($dir, 0, -1);
			}

			$url = $dir . '/' . str_replace($pathinfo['dirname'] . '/', '', $url);
			$url = generate_board_url() . '/' . $url;
		}
	}
	
	// Behave as per HTTP/1.1 spec for others
	
	header('Location: ' . $url, true, $code);
	
	exit;
}


/**
* Generate board url (example: http://www.foo.bar/phpBB)
* @param bool $without_script_path if set to true the script path gets not appended (example: http://www.foo.bar)
*/
function generate_board_url($without_script_path = false)
{
	global $config, $user;

	$server_name = (!empty($_SERVER['SERVER_NAME'])) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME');
	$server_port = (!empty($_SERVER['SERVER_PORT'])) ? (int) $_SERVER['SERVER_PORT'] : (int) getenv('SERVER_PORT');

	$url = (($config['cookie_secure']) ? 'https://' : 'http://') . $server_name;

	// Forcing server vars is the only way to specify/override the protocol
	if (!$server_name)
	{
		$server_protocol = ($config['server_protocol']) ? $config['server_protocol'] : (($config['cookie_secure']) ? 'https://' : 'http://');
		$server_name = $config['server_name'];
		$server_port = (int) $config['server_port'];

		$url = $server_protocol . $server_name;
	}

	if ($server_port && (($config['cookie_secure'] && $server_port <> 443) || (!$config['cookie_secure'] && $server_port <> 80)))
	{
		$url .= ':' . $server_port;
	}

	if ($without_script_path)
	{
		return $url;
	}

	// Strip / from the end
	return $url . substr($user->page['root_script_path'], 0, -1);
}

/**
* Meta refresh assignment
*/
function meta_refresh($time, $url)
{
	global $smarty;

	$smarty->assign(
		'META' , '<meta http-equiv="refresh" content="' . $time . ';url=' . $url . '" />'
	);
}


?>
